import { STORAGE_KEYS } from '@/constants/storage';
import { storageService } from '@/services/storage';
import type { OperationResult } from '@/types/common/base';
import type { 
  IStudent, 
  IStudentCreateRequest, 
  IStudentUpdateRequest, 
  IStudentQueryParams,
  IStudentStatistics,
  IStudentSummary
} from '@/types/student/student';
import { StudentStatusEnum } from '@/types/student/enums';

/**
 * 学生验证结果接口
 */
interface IStudentValidationResult {
  /** 是否验证通过 */
  isValid: boolean;
  /** 错误信息列表 */
  errors: string[];
}

/**
 * 学生服务类
 * @description 负责学生数据的增删改查和业务逻辑处理
 */
export class StudentService {
  /**
   * 获取所有学生
   * @param queryParams 查询参数
   * @returns 学生列表
   */
  async getAllStudents(queryParams?: IStudentQueryParams): Promise<OperationResult<IStudent[]>> {
    try {
      const result = await storageService.getItem<IStudent[]>(STORAGE_KEYS.STUDENTS);
      
      if (!result.success) {
        // 如果没有数据，返回空数组
        if (result.errorCode === 'INVALID_DATA_FORMAT') {
          return {
            success: true,
            data: []
          };
        }
        return result;
      }

      let students = result.data || [];

      // 过滤已删除的学生
      students = students.filter(student => student.status !== StudentStatusEnum.DELETED);

      // 应用查询参数
      if (queryParams) {
        students = this.filterStudents(students, queryParams);
      }

      return {
        success: true,
        data: students
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取学生列表失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据ID获取学生
   * @param id 学生ID
   * @returns 学生信息
   */
  async getStudentById(id: string): Promise<OperationResult<IStudent>> {
    try {
      const studentsResult = await this.getAllStudents();
      if (!studentsResult.success) {
        return studentsResult;
      }

      const student = studentsResult.data.find(s => s.id === id);
      if (!student) {
        return {
          success: false,
          error: '学生不存在'
        };
      }

      return {
        success: true,
        data: student
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取学生信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据学号获取学生
   * @param studentId 学号
   * @returns 学生信息
   */
  async getStudentByStudentId(studentId: string): Promise<OperationResult<IStudent>> {
    try {
      const studentsResult = await this.getAllStudents();
      if (!studentsResult.success) {
        return studentsResult;
      }

      const student = studentsResult.data.find(s => s.studentId === studentId);
      if (!student) {
        return {
          success: false,
          error: '学生不存在'
        };
      }

      return {
        success: true,
        data: student
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取学生信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 创建学生
   * @param studentData 学生数据
   * @returns 创建的学生信息
   */
  async createStudent(studentData: IStudentCreateRequest): Promise<OperationResult<IStudent>> {
    try {
      // 数据验证
      const validationResult = this.validateStudentData(studentData);
      if (!validationResult.isValid) {
        return {
          success: false,
          error: validationResult.errors.join('; ')
        };
      }

      // 检查学号是否已存在
      const existingStudentResult = await this.getStudentByStudentId(studentData.studentId);
      if (existingStudentResult.success) {
        return {
          success: false,
          error: `学号 ${studentData.studentId} 已存在`
        };
      }

      // 获取现有学生列表
      const studentsResult = await this.getAllStudents();
      if (!studentsResult.success) {
        return studentsResult;
      }

      const students = studentsResult.data;

      // 创建新学生对象
      const now = Date.now();
      const newStudent: IStudent = {
        id: this.generateStudentId(),
        ...studentData,
        status: studentData.status || StudentStatusEnum.ACTIVE,
        createdAt: now,
        updatedAt: now
      };

      // 添加到学生列表
      students.push(newStudent);

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.STUDENTS, students, {
        createBackup: true
      });

      if (!saveResult.success) {
        return saveResult;
      }

      return {
        success: true,
        data: newStudent
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '创建学生失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 更新学生信息
   * @param id 学生ID
   * @param updateData 更新数据
   * @returns 更新后的学生信息
   */
  async updateStudent(id: string, updateData: Omit<IStudentUpdateRequest, 'id'>): Promise<OperationResult<IStudent>> {
    try {
      // 获取现有学生列表
      const studentsResult = await this.getAllStudents();
      if (!studentsResult.success) {
        return studentsResult;
      }

      const students = studentsResult.data;
      const studentIndex = students.findIndex(s => s.id === id);

      if (studentIndex === -1) {
        return {
          success: false,
          error: '学生不存在'
        };
      }

      const existingStudent = students[studentIndex];

      // 如果更新学号，检查新学号是否已存在
      if (updateData.studentId && updateData.studentId !== existingStudent.studentId) {
        const existingStudentResult = await this.getStudentByStudentId(updateData.studentId);
        if (existingStudentResult.success) {
          return {
            success: false,
            error: `学号 ${updateData.studentId} 已存在`
          };
        }
      }

      // 合并更新数据
      const updatedStudent: IStudent = {
        ...existingStudent,
        ...updateData,
        id, // 确保ID不被修改
        updatedAt: Date.now()
      };

      // 验证更新后的数据
      const validationResult = this.validateStudentData(updatedStudent);
      if (!validationResult.isValid) {
        return {
          success: false,
          error: validationResult.errors.join('; ')
        };
      }

      // 更新学生列表
      students[studentIndex] = updatedStudent;

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.STUDENTS, students, {
        createBackup: true
      });

      if (!saveResult.success) {
        return saveResult;
      }

      return {
        success: true,
        data: updatedStudent
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新学生信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 删除学生（软删除）
   * @param id 学生ID
   * @returns 操作结果
   */
  async deleteStudent(id: string): Promise<OperationResult<void>> {
    try {
      // 检查学生是否有关联的课表
      const hasScheduleResult = await this.checkStudentHasSchedule(id);
      if (!hasScheduleResult.success) {
        return hasScheduleResult;
      }

      if (hasScheduleResult.data) {
        return {
          success: false,
          error: '该学生有关联的课程安排，请先删除相关课表后再删除学生'
        };
      }

      // 软删除：将状态设置为已删除
      const updateResult = await this.updateStudent(id, {
        status: StudentStatusEnum.DELETED
      });

      if (!updateResult.success) {
        return updateResult;
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '删除学生失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 永久删除学生
   * @param id 学生ID
   * @returns 操作结果
   */
  async permanentDeleteStudent(id: string): Promise<OperationResult<void>> {
    try {
      // 检查学生是否有关联的课表
      const hasScheduleResult = await this.checkStudentHasSchedule(id);
      if (!hasScheduleResult.success) {
        return hasScheduleResult;
      }

      if (hasScheduleResult.data) {
        return {
          success: false,
          error: '该学生有关联的课程安排，请先删除相关课表后再删除学生'
        };
      }

      // 获取现有学生列表
      const studentsResult = await this.getAllStudents();
      if (!studentsResult.success) {
        return studentsResult;
      }

      const students = studentsResult.data;
      const filteredStudents = students.filter(s => s.id !== id);

      if (filteredStudents.length === students.length) {
        return {
          success: false,
          error: '学生不存在'
        };
      }

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.STUDENTS, filteredStudents, {
        createBackup: true
      });

      if (!saveResult.success) {
        return saveResult;
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '永久删除学生失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 批量删除学生
   * @param ids 学生ID列表
   * @returns 操作结果
   */
  async batchDeleteStudents(ids: string[]): Promise<OperationResult<{ successCount: number; failedCount: number; errors: string[] }>> {
    try {
      let successCount = 0;
      let failedCount = 0;
      const errors: string[] = [];

      for (const id of ids) {
        const result = await this.deleteStudent(id);
        if (result.success) {
          successCount++;
        } else {
          failedCount++;
          errors.push(`学生 ${id}: ${result.error}`);
        }
      }

      return {
        success: true,
        data: {
          successCount,
          failedCount,
          errors
        }
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '批量删除学生失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取学生统计信息
   * @returns 统计信息
   */
  async getStudentStatistics(): Promise<OperationResult<IStudentStatistics>> {
    try {
      const studentsResult = await this.getAllStudents();
      if (!studentsResult.success) {
        return studentsResult;
      }

      const students = studentsResult.data;

      // 基础统计
      const totalCount = students.length;
      const activeCount = students.filter(s => s.status === StudentStatusEnum.ACTIVE).length;
      const inactiveCount = students.filter(s => s.status === StudentStatusEnum.INACTIVE).length;
      const graduatedCount = students.filter(s => s.status === StudentStatusEnum.GRADUATED).length;

      // 年级分布统计
      const gradeMap = new Map<string, number>();
      students.forEach(student => {
        if (student.grade) {
          gradeMap.set(student.grade, (gradeMap.get(student.grade) || 0) + 1);
        }
      });
      const gradeDistribution = Array.from(gradeMap.entries()).map(([grade, count]) => ({
        grade,
        count
      }));

      // 班级分布统计
      const classMap = new Map<string, number>();
      students.forEach(student => {
        if (student.class) {
          classMap.set(student.class, (classMap.get(student.class) || 0) + 1);
        }
      });
      const classDistribution = Array.from(classMap.entries()).map(([className, count]) => ({
        class: className,
        count
      }));

      // 性别分布统计
      const genderMap = new Map<'male' | 'female' | 'other', number>();
      students.forEach(student => {
        if (student.gender) {
          genderMap.set(student.gender, (genderMap.get(student.gender) || 0) + 1);
        }
      });
      const genderDistribution = Array.from(genderMap.entries()).map(([gender, count]) => ({
        gender,
        count
      }));

      const statistics: IStudentStatistics = {
        totalCount,
        activeCount,
        inactiveCount,
        graduatedCount,
        gradeDistribution,
        classDistribution,
        genderDistribution
      };

      return {
        success: true,
        data: statistics
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取学生统计信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取学生简要信息列表
   * @param queryParams 查询参数
   * @returns 学生简要信息列表
   */
  async getStudentSummaries(queryParams?: IStudentQueryParams): Promise<OperationResult<IStudentSummary[]>> {
    try {
      const studentsResult = await this.getAllStudents(queryParams);
      if (!studentsResult.success) {
        return studentsResult;
      }

      const summaries: IStudentSummary[] = studentsResult.data.map(student => ({
        id: student.id,
        name: student.name,
        studentId: student.studentId,
        grade: student.grade,
        class: student.class,
        status: student.status,
        avatar: student.avatar
      }));

      return {
        success: true,
        data: summaries
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取学生简要信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 搜索学生
   * @param keyword 搜索关键词
   * @param limit 结果数量限制
   * @returns 搜索结果
   */
  async searchStudents(keyword: string, limit: number = 10): Promise<OperationResult<IStudent[]>> {
    try {
      if (!keyword.trim()) {
        return {
          success: true,
          data: []
        };
      }

      const studentsResult = await this.getAllStudents();
      if (!studentsResult.success) {
        return studentsResult;
      }

      const students = studentsResult.data;
      const lowerKeyword = keyword.toLowerCase();

      const matchedStudents = students.filter(student => 
        student.name.toLowerCase().includes(lowerKeyword) ||
        student.studentId.toLowerCase().includes(lowerKeyword) ||
        (student.phone && student.phone.includes(keyword)) ||
        (student.parentName && student.parentName.toLowerCase().includes(lowerKeyword)) ||
        (student.grade && student.grade.toLowerCase().includes(lowerKeyword)) ||
        (student.class && student.class.toLowerCase().includes(lowerKeyword))
      );

      // 按相关性排序（姓名匹配优先）
      matchedStudents.sort((a, b) => {
        const aNameMatch = a.name.toLowerCase().includes(lowerKeyword);
        const bNameMatch = b.name.toLowerCase().includes(lowerKeyword);
        
        if (aNameMatch && !bNameMatch) return -1;
        if (!aNameMatch && bNameMatch) return 1;
        
        return a.name.localeCompare(b.name);
      });

      return {
        success: true,
        data: matchedStudents.slice(0, limit)
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '搜索学生失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 验证学生数据
   * @param studentData 学生数据
   * @returns 验证结果
   */
  private validateStudentData(studentData: Partial<IStudent>): IStudentValidationResult {
    const errors: string[] = [];

    // 必填字段验证
    if (!studentData.name || !studentData.name.trim()) {
      errors.push('学生姓名不能为空');
    }

    if (!studentData.studentId || !studentData.studentId.trim()) {
      errors.push('学号不能为空');
    }

    // 格式验证
    if (studentData.name && studentData.name.length > 50) {
      errors.push('学生姓名长度不能超过50个字符');
    }

    if (studentData.studentId && studentData.studentId.length > 20) {
      errors.push('学号长度不能超过20个字符');
    }

    if (studentData.phone && !/^1[3-9]\d{9}$/.test(studentData.phone)) {
      errors.push('手机号格式不正确');
    }

    if (studentData.parentPhone && !/^1[3-9]\d{9}$/.test(studentData.parentPhone)) {
      errors.push('家长手机号格式不正确');
    }

    if (studentData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(studentData.email)) {
      errors.push('邮箱格式不正确');
    }

    if (studentData.age && (studentData.age < 3 || studentData.age > 100)) {
      errors.push('年龄必须在3-100岁之间');
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  }

  /**
   * 过滤学生列表
   * @param students 学生列表
   * @param queryParams 查询参数
   * @returns 过滤后的学生列表
   */
  private filterStudents(students: IStudent[], queryParams: IStudentQueryParams): IStudent[] {
    return students.filter(student => {
      // 姓名模糊搜索
      if (queryParams.name && !student.name.toLowerCase().includes(queryParams.name.toLowerCase())) {
        return false;
      }

      // 学号精确匹配
      if (queryParams.studentId && student.studentId !== queryParams.studentId) {
        return false;
      }

      // 年级匹配
      if (queryParams.grade && student.grade !== queryParams.grade) {
        return false;
      }

      // 班级匹配
      if (queryParams.class && student.class !== queryParams.class) {
        return false;
      }

      // 状态匹配
      if (queryParams.status && student.status !== queryParams.status) {
        return false;
      }

      // 性别匹配
      if (queryParams.gender && student.gender !== queryParams.gender) {
        return false;
      }

      // 年龄范围
      if (queryParams.minAge && (!student.age || student.age < queryParams.minAge)) {
        return false;
      }

      if (queryParams.maxAge && (!student.age || student.age > queryParams.maxAge)) {
        return false;
      }

      // 入学日期范围
      if (queryParams.enrollmentStartDate && (!student.enrollmentDate || student.enrollmentDate < queryParams.enrollmentStartDate)) {
        return false;
      }

      if (queryParams.enrollmentEndDate && (!student.enrollmentDate || student.enrollmentDate > queryParams.enrollmentEndDate)) {
        return false;
      }

      return true;
    });
  }

  /**
   * 检查学生是否有关联的课表
   * @param studentId 学生ID
   * @returns 检查结果
   */
  private async checkStudentHasSchedule(studentId: string): Promise<OperationResult<boolean>> {
    try {
      // 检查课程模板
      const templatesResult = await storageService.getItem(STORAGE_KEYS.SCHEDULE_TEMPLATES);
      if (templatesResult.success && templatesResult.data) {
        const templates = Array.isArray(templatesResult.data) ? templatesResult.data : [];
        const hasTemplate = templates.some((template: any) => template.studentId === studentId);
        if (hasTemplate) {
          return {
            success: true,
            data: true
          };
        }
      }

      // 检查课程实例
      const instancesResult = await storageService.getItem(STORAGE_KEYS.SCHEDULE_INSTANCES);
      if (instancesResult.success && instancesResult.data) {
        const instances = Array.isArray(instancesResult.data) ? instancesResult.data : [];
        const hasInstance = instances.some((instance: any) => instance.studentId === studentId);
        if (hasInstance) {
          return {
            success: true,
            data: true
          };
        }
      }

      return {
        success: true,
        data: false
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '检查学生课表关联失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 生成学生ID
   * @returns 学生ID
   */
  private generateStudentId(): string {
    const timestamp = Date.now().toString(36);
    const randomStr = Math.random().toString(36).substr(2, 9);
    return `student_${timestamp}_${randomStr}`;
  }
}

/**
 * 默认学生服务实例
 */
export const studentService = new StudentService();